package com.wing.user.feign;

import com.wing.user.model.dingRequest.OapiV2DepartmentListsubRequest;
import com.wing.user.model.dingResponse.OapiV2DepartmentListsubResponse;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @author
 */
@Component
@Service
public class DingTalkClientFallback implements DingTalkClient {

    @Autowired
    DingTalkClient dingTalkClient;


    @Override
    public OapiV2DepartmentListsubResponse listSubDepartments(String access_token, OapiV2DepartmentListsubRequest request) throws Exception {
        return dingTalkClient.listSubDepartments(access_token,request);
    }





    private static final String APP_KEY = "ding82iytsnrfsu4bb7p";
    private static final String APP_SECRET = "sE3mhPsMaTr-MgmR6vRpKEZmRyBR9YpJeUnu-4kV1MLafAK7U0sgW07eBancMwSF";
    private static final String GET_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken?appkey=" + APP_KEY + "&appsecret=" + APP_SECRET;

    public static String getAccessToken() throws Exception {
        URL url = new URL(GET_ACCESS_TOKEN_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            JSONObject jsonObject = new JSONObject(response.toString());
            return jsonObject.getString("access_token");
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }
    }

}

